package com.vibration.baseinfo.service.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.*;

import ComputeFinal.compute;
import ComputeTC2.computeTC2;
import ComputeVParam.computeVParam;
import com.mathworks.toolbox.javabuilder.MWClassID;
import com.mathworks.toolbox.javabuilder.MWException;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import com.mathworks.toolbox.javabuilder.MWStringArray;
import com.vibration.baseinfo.domain.TaskCountModel;
import com.vibration.baseinfo.domain.*;
import com.vibration.baseinfo.service.ICzEquipmentService;
import com.vibration.baseinfo.service.ICzTaskDataService;
import com.vibration.baseinfo.service.ICzTemperatureDataService;
import com.vibration.common.annotation.DataScope;
import com.vibration.common.config.VibrationConfig;
import com.vibration.common.constant.Constants;
import com.vibration.common.core.redis.RedisCache;
import com.vibration.common.utils.StringUtils;
import com.vibration.matlab.GetPlotImage;
import com.vibration.matlab.TransInfo;
import com.vibration.socket.domain.DataCollection;
import com.vibration.socket.domain.DataList;
import com.vibration.socket.util.FFTUtil;
import com.vibration.socket.util.SocketUtil;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.vibration.baseinfo.mapper.CzCollectionTaskMapper;
import com.vibration.baseinfo.service.ICzCollectionTaskService;
import tempPlot.temp;

/**
 * 任务数据Service业务层处理
 * 
 * @author wu
 * @date 2022-08-11
 */
@Service
public class CzCollectionTaskServiceImpl implements ICzCollectionTaskService 
{
    @Autowired
    private CzCollectionTaskMapper czCollectionTaskMapper;
    @Autowired
    private ICzTaskDataService taskDataService;

    @Autowired
    private ICzTemperatureDataService temperatureDataService;
    @Autowired
    private ICzEquipmentService equipmentService;


    private static TransInfo transInfo;
    @Autowired
    private RedisCache redisCache;


    /**
     * 查询任务数据
     * 
     * @param id 任务数据主键
     * @return 任务数据
     */
    @Override
    public CzCollectionTask selectCzCollectionTaskById(Long id) throws Exception {
        CzCollectionTask collectionTask = czCollectionTaskMapper.selectCzCollectionTaskById(id);
        CzEquipment equipment = equipmentService.selectEquipmentInfo(collectionTask.getEquipmentSn());
        if("0".equals(collectionTask.getType())){
            //查询任务数据
            CzTaskData q =new CzTaskData();
            q.setTaskId(id);
            List<CzTaskData> taskDataList = taskDataService.selectCzTaskDataList(q);
            //不处理数据
            List<Float> xData1 = new ArrayList<>();
            List<Float> yData1 = new ArrayList<>();
            List<Float> zData1 = new ArrayList<>();
            //数据处理
            List<Float> xData = new ArrayList<>();
            List<Float> yData = new ArrayList<>();
            List<Float> zData = new ArrayList<>();

            for (CzTaskData taskData : taskDataList) {
                String[] xArray = taskData.getDataX().split(",");
                String[] yArray = taskData.getDataY().split(",");
                String[] zArray = taskData.getDataZ().split(",");
                List<Float> tempX = new ArrayList<>();
                List<Float> tempY = new ArrayList<>();
                List<Float> tempZ = new ArrayList<>();
                for (int i = 0; i < xArray.length; i++) {
                    tempX.add(Float.parseFloat(xArray[i])*100);
                    tempY.add(Float.parseFloat(yArray[i])*100-1500);
                    tempZ.add(Float.parseFloat(zArray[i])*100+1500);
                    xData1.add(Float.parseFloat(xArray[i]));
                    yData1.add(Float.parseFloat(yArray[i]));
                    zData1.add(Float.parseFloat(zArray[i]));
                }
                xData.addAll(tempX);
                yData.addAll(tempY);
                zData.addAll(tempZ);
            }
            DataList dataList = new DataList();
            dataList.setDataX(xData);
            dataList.setDataY(yData);
            dataList.setDataZ(zData);
            collectionTask.setDataList(dataList);

            if(collectionTask.getStartData()!=null && collectionTask.getEndData()!=null && collectionTask.getInversionInterval()!=null){
                //选中该数据
                List<Float> xData2 = xData1.subList(collectionTask.getStartData(),collectionTask.getEndData());
                List<Float> yData2 = yData1.subList(collectionTask.getStartData(),collectionTask.getEndData());
                List<Float> zData2 = zData1.subList(collectionTask.getStartData(),collectionTask.getEndData());
                //计算谱比 及平均值
                List<HVData> hvDataList = new ArrayList<>();
                //每组长度
                int L = xData2.size()/collectionTask.getInversionInterval();
                //谱比数据
                for (int i = 0; i < collectionTask.getInversionInterval(); i++) {
                    List<Double> x = new ArrayList<>();
                    List<Double> y = new ArrayList<>();
                    List<Double> z = new ArrayList<>();
                    for (int j = i*L; j < i*L+L; j++) {
                        x.add(xData2.get(j).doubleValue());
                        y.add(yData2.get(j).doubleValue());
                        z.add(zData2.get(j).doubleValue());
                    }
                    //计算谱比
                    double[] xxx =new double[x.size()];
                    double[] yyy =new double[y.size()];
                    double[] zzz =new double[z.size()];
                    for (int j = 0; j < x.size(); j++) {
                        xxx[j] = x.get(j);
                        yyy[j] = y.get(j);
                        zzz[j] = z.get(j);
                    }
                    //计算频率
                    Float sampleInterval =equipment.getSampleInterval();
                    //float计算丢失精度，这里转为double计算
                    Double sampleIntervalD = sampleInterval.doubleValue();
                    Double fs = 1/(sampleIntervalD/1000);
                    Map<String,double[]> hv = FFTUtil.hv(fs.intValue(),xxx,yyy,zzz);
                    double[] f = hv.get("f");
                    double[] h = hv.get("hv");
                    HVData hvData = new HVData();
                    hvData.setFrequency(f);
                    hvData.setHv(h);
                    hvDataList.add(hvData);
                }
                //计算平均值
                //double[] ff = hvDataList.get(0).getFrequency();
                double[] ff = new double[hvDataList.get(0).getFrequency().length-1];
                double[] hh =  new double[hvDataList.get(0).getHv().length-1];
                for (int i = 1; i < hvDataList.get(0).getFrequency().length; i++) {
                    ff[i-1] = hvDataList.get(0).getFrequency()[i];
                    double total = 0.0;
                    for (int j = 0; j < hvDataList.size(); j++) {
                        total+=hvDataList.get(j).getHv()[i];
                    }
                    //保留6位小数
                    BigDecimal two = new BigDecimal(total/hvDataList.size());
                    double three = two.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();
                    hh[i-1] = three;
                }
                //谱比平均值  echarts显示用
                HVData hvData = new HVData();
                hvData.setFrequency(ff);
                hvData.setHv(hh);
                collectionTask.setHvData(hvData);
            }
        }else if("1".equals(collectionTask.getType())){
            CzTemperatureData q = new CzTemperatureData();
            q.setTaskId(collectionTask.getId());
            List<CzTemperatureData> temperatureDataList = temperatureDataService.selectCzTemperatureDataList(q);
            collectionTask.setTemperatureDataList(temperatureDataList);
        }

        return collectionTask;
    }

    /**
     * 查询任务数据列表
     * 
     * @param czCollectionTask 任务数据
     * @return 任务数据
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<CzCollectionTask> selectCzCollectionTaskList(CzCollectionTask czCollectionTask)
    {
        List<CzCollectionTask> list = czCollectionTaskMapper.selectCzCollectionTaskList(czCollectionTask);
        list.forEach(task -> {
            if("1".equals(task.getType())){
                task.setDataNumber(temperatureDataService.dataCountByTaskId(task.getId()));
            }else {
                task.setDataNumber(taskDataService.dataCountByTaskId(task.getId()));
            }
        });
        return list;
    }

    /**
     * 新增任务数据
     * 
     * @param czCollectionTask 任务数据
     * @return 结果
     */
    @Override
    public CzCollectionTask insertCzCollectionTask(CzCollectionTask czCollectionTask)
    {
        if("0".equals(czCollectionTask.getType())){
            czCollectionTask.setTaskStatus("0");
        }else if ("1".equals(czCollectionTask.getType())){
            czCollectionTask.setTaskStatus("1");
            czCollectionTask.setBeginTime(new Date());
        }
        czCollectionTaskMapper.insertCzCollectionTask(czCollectionTask);
        if("0".equals(czCollectionTask.getType())){
            //将任务添加到redis
            TaskModel taskModel = new TaskModel();
            taskModel.setTaskId(czCollectionTask.getId());
            taskModel.setSn(czCollectionTask.getEquipmentSn());
            Long startTime =  czCollectionTask.getBeginTime().getTime();
            taskModel.setStartTime(startTime);
            taskModel.setEndTime(startTime+(czCollectionTask.getDuration()*1000));
            Map<String,List<TaskModel>> taskModelMap = redisCache.getCacheObject("task");
            if(taskModelMap!=null){
                List<TaskModel> taskModelList = taskModelMap.get(czCollectionTask.getEquipmentSn());
                if(taskModelList!=null){
                    taskModelList.add(taskModel);
                }else {
                    taskModelList = new ArrayList<>();
                    taskModelList.add(taskModel);
                }
                taskModelMap.put(czCollectionTask.getEquipmentSn(),taskModelList);
            }else {
                taskModelMap = new HashMap<String,List<TaskModel>>();
                List<TaskModel> taskModelList = new ArrayList<>();
                taskModelList.add(taskModel);
                taskModelMap.put(czCollectionTask.getEquipmentSn(),taskModelList);
            }
            redisCache.setCacheObject("task",taskModelMap);
            Map<String,List<TaskModel>> a = redisCache.getCacheObject("task");
            System.err.println("====================>震动任务创建");
            System.err.println(a);
        }else if("1".equals(czCollectionTask.getType())){
            //根据设备sn获取设备gyroscopeCode
            CzEquipment ce = equipmentService.selectEquipmentInfo(czCollectionTask.getEquipmentSn());
            czCollectionTask.setEquipmentCode( ce.getGyroscopeCode());
            //将正在采集的任务放入公共变量
            SocketUtil.ontaskMap.put(czCollectionTask.getId(),czCollectionTask);

            DataCollection dataCollection = SocketUtil.gyroscopeSocketMap.get(ce.getGyroscopeCode());
            System.err.println("================>温度采集线程开始");
            if(dataCollection!=null){
                new pollThread(dataCollection,czCollectionTask.getId());
            }
            System.err.println("================>温度采集线程结束");
        }
        //新增便开始采集
        //SocketUtil.taskMap.put(czCollectionTask.getEquipmentSn(),czCollectionTask);
        return czCollectionTask;
    }

    /**
     * 修改任务数据
     * 
     * @param czCollectionTask 任务数据
     * @return 结果
     */
    @Override
    public int updateCzCollectionTask(CzCollectionTask czCollectionTask)
    {
        return czCollectionTaskMapper.updateCzCollectionTask(czCollectionTask);
    }

    /**
     * 批量删除任务数据
     * 
     * @param ids 需要删除的任务数据主键
     * @return 结果
     */
    @Override
    public int deleteCzCollectionTaskByIds(Long[] ids)
    {
        return czCollectionTaskMapper.deleteCzCollectionTaskByIds(ids);
    }

    /**
     * 删除任务数据信息
     * 
     * @param id 任务数据主键
     * @return 结果
     */
    @Override
    public int deleteCzCollectionTaskById(Long id)
    {
        return czCollectionTaskMapper.deleteCzCollectionTaskById(id);
    }


    /**
     * 时域频域分析
     * @param czCollectionTask
     * @return
     * @throws MWException
     */
    public CzCollectionTask analyse(CzCollectionTask czCollectionTask) throws MWException {
        String descPath=VibrationConfig.getInversionPath()+"/"+ czCollectionTask.getId();
        if(!new File(descPath).exists()){
            new File(descPath).mkdirs();
        }
        CzEquipment equipment = equipmentService.selectEquipmentInfo(czCollectionTask.getEquipmentSn());

        CzTaskData q =new CzTaskData();
        q.setTaskId(czCollectionTask.getId());
        List<CzTaskData> taskDataList = taskDataService.selectCzTaskDataList(q);
        List<Float> xData1 = new ArrayList<>();
        List<Float> yData1 = new ArrayList<>();
        List<Float> zData1 = new ArrayList<>();

        float sampleInterval =equipment.getSampleInterval();
        float fs = 1/(sampleInterval/1000);
        for (CzTaskData taskData : taskDataList) {
            String[] xArray = taskData.getDataX().split(",");
            String[] yArray = taskData.getDataY().split(",");
            String[] zArray = taskData.getDataZ().split(",");
            for (int i = 0; i < xArray.length; i++) {
                xData1.add(Float.parseFloat(xArray[i]));
                yData1.add(Float.parseFloat(yArray[i]));
                zData1.add(Float.parseFloat(zArray[i]));
            }
        }
        float[] getAllXData=new float[xData1.size()];
        for(int i=0;i<xData1.size();i++){
            getAllXData[i]=xData1.get(i);
        }
        float[] getAllYData=new float[yData1.size()];
        for(int i=0;i<yData1.size();i++){
            getAllYData[i]=yData1.get(i);
        }
        float[] getAllZData=new float[zData1.size()];
        for(int i=0;i<zData1.size();i++){
            getAllZData[i]=zData1.get(i);
        }
        //定义二维数组
        double[][] getAllData=new double[getAllXData.length][3];
        //把一维数组合并为二维
        for(int m=0;m<getAllXData.length;m++){
            getAllData[m][0]=getAllXData[m];
            getAllData[m][1]=getAllYData[m];
            getAllData[m][2]=getAllZData[m];
        }
        String newpathName=VibrationConfig.getInversionPath()+"/"+ czCollectionTask.getId()+"/"+"ALLXYZData.txt";
        writeArrayToTxt2(getAllData,newpathName);
        System.out.println("得到频率"+fs);
        //选中该数据
        List<Float> xData2 = xData1.subList(czCollectionTask.getAnalyseStart(),czCollectionTask.getAnalyseEnd());
        List<Float> yData2 = yData1.subList(czCollectionTask.getAnalyseStart(),czCollectionTask.getAnalyseEnd());
        List<Float> zData2 = zData1.subList(czCollectionTask.getAnalyseStart(),czCollectionTask.getAnalyseEnd());
        double[] xxx=null;
        double[] yyy=null;
        double[] zzz=null;
        //计算谱比
        xxx =new double[xData2.size()];
        yyy =new double[yData2.size()];
        zzz =new double[zData2.size()];
        for (int j = 0; j < xData2.size(); j++) {
                xxx[j] = xData2.get(j);
                yyy[j] = yData2.get(j);
                zzz[j] = zData2.get(j);
        }
    /**
     * 计算x曲线的值
    */
        MWNumericArray xDatamata = new MWNumericArray(xxx, MWClassID.DOUBLE);
        computeVParam compute=new computeVParam();
        MWNumericArray Length = new MWNumericArray(xxx.length, MWClassID.DOUBLE);
        String xPlotfilePath= VibrationConfig.getInversionPath()+"/"+czCollectionTask.getId()+"/";
        String xPlotfileName="xComputePlot";
        MWStringArray xStringArrayPath=new MWStringArray(xPlotfilePath);
        MWStringArray xStringArrayName=new MWStringArray(xPlotfileName);
        Object[] respnseX=compute.ComputeVParam(7,xDatamata,fs,Length,xStringArrayPath,xStringArrayName);

        //得到最大值
        MWNumericArray xMaxData=(MWNumericArray)respnseX[0];
        double[][] xMaxDataArray=(double[][])xMaxData.toDoubleArray();
        double[] xMax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xMaxDataArray[0][0]))))};
        //得到最小值
        MWNumericArray xMinData=(MWNumericArray)respnseX[1];
        double[][] xMinDataArray=(double[][])xMinData.toDoubleArray();
        double[] xMin={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xMinDataArray[0][0]))))};
        //得到平均值
        MWNumericArray xAvgData=(MWNumericArray)respnseX[2];
        double[][] xAvgDataArray=(double[][])xAvgData.toDoubleArray();
        double[] xAvg={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xAvgDataArray[0][0]))))};
        //得到标准差
        MWNumericArray xStdData=(MWNumericArray)respnseX[3];
        double[][] xStdDataArray=(double[][])xStdData.toDoubleArray();
        double[] xStd={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xStdDataArray[0][0]))))};
        //得到峰值频率
        MWNumericArray xFmaxData=(MWNumericArray)respnseX[4];
        double[][] xFmaxDataArray=(double[][])xFmaxData.toDoubleArray();
        double[] xFmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xFmaxDataArray[0][0]))))};
        //得到幅度
        MWNumericArray xAmaxData=(MWNumericArray)respnseX[5];
        double[][] xAmaxDataArray=(double[][])xAmaxData.toDoubleArray();
        double[] xAmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xAmaxDataArray[0][0]))))};

        //定义二维数组
        double[][] getComputeTotalDataX=new double[1][6];
        //把一维数组合并为二维
        for(int m=0;m<1;m++){
            getComputeTotalDataX[m][0]=xMax[0];
            getComputeTotalDataX[m][1]=xMin[0];
            getComputeTotalDataX[m][2]=xAvg[0];
            getComputeTotalDataX[m][3]=xStd[0];
            getComputeTotalDataX[m][4]=xFmax[0];
            getComputeTotalDataX[m][5]=xAmax[0];
        }
        /**
         * 写入数据
         */
        String XComputePathName=VibrationConfig.getInversionPath()+"/"+ czCollectionTask.getId()+"/"+"XComputeData.txt";
        writeVibDataToTxt(getComputeTotalDataX,XComputePathName);


        /**
         * 计算y曲线的值
         */
        MWNumericArray yDatamata = new MWNumericArray(yyy, MWClassID.DOUBLE);
        computeVParam compute2=new computeVParam();
        MWNumericArray Length2 = new MWNumericArray(yyy.length, MWClassID.DOUBLE);
        String yPlotfilePath= VibrationConfig.getInversionPath()+"/"+ czCollectionTask.getId()+"/";
        String yPlotfileName="yComputePlot";
        MWStringArray yStringArrayPath=new MWStringArray(yPlotfilePath);
        MWStringArray yStringArrayName=new MWStringArray(yPlotfileName);
        Object[] respnseY=compute2.ComputeVParam(7,yDatamata,fs,Length2,yStringArrayPath,yStringArrayName);


        //得到最大值
        MWNumericArray yMaxData=(MWNumericArray)respnseY[0];
        double[][] yMaxDataArray=(double[][])yMaxData.toDoubleArray();
        double[] yMax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yMaxDataArray[0][0]))))};
        //得到最小值
        MWNumericArray yMinData=(MWNumericArray)respnseY[1];
        double[][] yMinDataArray=(double[][])yMinData.toDoubleArray();
        double[] yMin={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yMinDataArray[0][0]))))};
        //得到平均值
        MWNumericArray yAvgData=(MWNumericArray)respnseY[2];
        double[][] yAvgDataArray=(double[][])yAvgData.toDoubleArray();
        double[] yAvg={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yAvgDataArray[0][0]))))};
        //得到标准差
        MWNumericArray yStdData=(MWNumericArray)respnseY[3];
        double[][] yStdDataArray=(double[][])yStdData.toDoubleArray();
        double[] yStd={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yStdDataArray[0][0]))))};
        //得到峰值频率
        MWNumericArray yFmaxData=(MWNumericArray)respnseY[4];
        double[][] yFmaxDataArray=(double[][])yFmaxData.toDoubleArray();
        double[] yFmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yFmaxDataArray[0][0]))))};
        //得到幅度
        MWNumericArray yAmaxData=(MWNumericArray)respnseY[5];
        double[][] yAmaxDataArray=(double[][])yAmaxData.toDoubleArray();
        double[] yAmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yAmaxDataArray[0][0]))))};


        //定义二维数组
        double[][] getComputeTotalDataY=new double[1][6];
        //把一维数组合并为二维
        for(int m=0;m<1;m++){
            getComputeTotalDataY[m][0]=yMax[0];
            getComputeTotalDataY[m][1]=yMin[0];
            getComputeTotalDataY[m][2]=yAvg[0];
            getComputeTotalDataY[m][3]=yStd[0];
            getComputeTotalDataY[m][4]=yFmax[0];
            getComputeTotalDataY[m][5]=yAmax[0];
        }
        /**
         * 写入数据
         */
        String YComputePathName=VibrationConfig.getInversionPath()+"/"+czCollectionTask.getId()+"/"+"YComputeData.txt";
        writeVibDataToTxt(getComputeTotalDataY,YComputePathName);



        /**
         * 计算z曲线的值
         */
        MWNumericArray zDatamata = new MWNumericArray(zzz, MWClassID.DOUBLE);
        computeVParam compute3=new computeVParam();
        MWNumericArray Length3 = new MWNumericArray(zzz.length, MWClassID.DOUBLE);
        String zPlotfilePath= VibrationConfig.getInversionPath()+"/"+ czCollectionTask.getId()+"/";
        String zPlotfileName="zComputePlot";
        MWStringArray zStringArrayPath=new MWStringArray(zPlotfilePath);
        MWStringArray zStringArrayName=new MWStringArray(zPlotfileName);
        Object[] respnseZ=compute3.ComputeVParam(7,zDatamata,fs,Length3,zStringArrayPath,zStringArrayName);


        //得到最大值
        MWNumericArray zMaxData=(MWNumericArray)respnseZ[0];
        double[][] zMaxDataArray=(double[][])zMaxData.toDoubleArray();
        double[] zMax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zMaxDataArray[0][0]))))};
        //得到最小值
        MWNumericArray zMinData=(MWNumericArray)respnseZ[1];
        double[][] zMinDataArray=(double[][])zMinData.toDoubleArray();
        double[] zMin={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zMinDataArray[0][0]))))};
        //得到平均值
        MWNumericArray zAvgData=(MWNumericArray)respnseZ[2];
        double[][] zAvgDataArray=(double[][])zAvgData.toDoubleArray();
        double[] zAvg={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zAvgDataArray[0][0]))))};
        //得到标准差
        MWNumericArray zStdData=(MWNumericArray)respnseZ[3];
        double[][] zStdDataArray=(double[][])zStdData.toDoubleArray();
        double[] zStd={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zStdDataArray[0][0]))))};

        //得到峰值频率
        MWNumericArray zFmaxData=(MWNumericArray)respnseZ[4];
        double[][] zFmaxDataArray=(double[][])zFmaxData.toDoubleArray();

        double[] zFmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zFmaxDataArray[0][0]))))};

        //得到幅度
        MWNumericArray zAmaxData=(MWNumericArray)respnseZ[5];
        double[][] zAmaxDataArray=(double[][])zAmaxData.toDoubleArray();
        double[] zAmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zAmaxDataArray[0][0]))))};


        //定义二维数组
        double[][] getComputeTotalDataZ=new double[1][6];
        //把一维数组合并为二维
        for(int m=0;m<1;m++){
            getComputeTotalDataZ[m][0]=zMax[0];
            getComputeTotalDataZ[m][1]=zMin[0];
            getComputeTotalDataZ[m][2]=zAvg[0];
            getComputeTotalDataZ[m][3]=zStd[0];
            getComputeTotalDataZ[m][4]=zFmax[0];
            getComputeTotalDataZ[m][5]=zAmax[0];
        }
        /**
         * 写入数据
         */
        String ZComputePathName=VibrationConfig.getInversionPath()+"/"+czCollectionTask.getId()+"/"+"ZComputeData.txt";
        writeVibDataToTxt(getComputeTotalDataZ,ZComputePathName);

        //写入计算的数据开始
        //定义二维数组
        double[][] getAllTotalData=new double[xxx.length][3];
        //把一维数组合并为二维
        for(int m=0;m<xxx.length;m++){
            getAllTotalData[m][0]=xxx[m];
            getAllTotalData[m][1]=yyy[m];
            getAllTotalData[m][2]=zzz[m];
        }
        String AllDataNewPathName=VibrationConfig.getInversionPath()+"/"+ czCollectionTask.getId()+"/"+"XYZData.txt";
        writeArrayToTxt2(getAllTotalData,AllDataNewPathName);

        CzCollectionTask task = new CzCollectionTask();
        task.setId(czCollectionTask.getId());
        task.setAnalyseStart(czCollectionTask.getAnalyseStart());
        task.setAnalyseEnd(czCollectionTask.getAnalyseEnd());
        task.setAnalyseStatus("1");
        String filePath= Constants.RESOURCE_PREFIX+VibrationConfig.getInversionImgPath() +"/"+ czCollectionTask.getId()+"/";
        task.setDataFile(filePath);
        czCollectionTaskMapper.updateCzCollectionTask(task);
        return task;
    }

    @Override
    public Long inversionTask(CzCollectionTask czCollectionTask) throws MWException {
        CzCollectionTask collectionTask = czCollectionTaskMapper.selectCzCollectionTaskById(czCollectionTask.getId());
        CzEquipment equipment = equipmentService.selectEquipmentInfo(collectionTask.getEquipmentSn());
        //设置状态为反演中
        collectionTask.setStartData(czCollectionTask.getStartData());
        collectionTask.setEndData(czCollectionTask.getEndData());
        collectionTask.setInversionInterval(czCollectionTask.getInversionInterval());
        collectionTask.setInversionSlice(czCollectionTask.getInversionSlice());
        collectionTask.setInversionStatus("1");
        czCollectionTaskMapper.updateCzCollectionTask(collectionTask);
        //反演标识
        SocketUtil.inversionTask = czCollectionTask.getId();

        String descPath=VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask;
        if(!new File(descPath).exists()){
            (new File(descPath)).mkdirs();
        }
        //查询任务数据
        CzTaskData q =new CzTaskData();
        q.setTaskId(collectionTask.getId());
        List<CzTaskData> taskDataList = taskDataService.selectCzTaskDataList(q);
        if(collectionTask.getStartData()!=null && collectionTask.getEndData()!=null && collectionTask.getInversionInterval()!=null){
            //处理数据
            List<Float> xData1 = new ArrayList<>();
            List<Float> yData1 = new ArrayList<>();
            List<Float> zData1 = new ArrayList<>();


            for (CzTaskData taskData : taskDataList) {
                String[] xArray = taskData.getDataX().split(",");
                String[] yArray = taskData.getDataY().split(",");
                String[] zArray = taskData.getDataZ().split(",");
                for (int i = 0; i < xArray.length; i++) {
                    xData1.add(Float.parseFloat(xArray[i]));
                    yData1.add(Float.parseFloat(yArray[i]));
                    zData1.add(Float.parseFloat(zArray[i]));
                }
            }

            float[] getAllXData=new float[xData1.size()];
            for(int i=0;i<xData1.size();i++){
                getAllXData[i]=xData1.get(i);
            }
            float[] getAllYData=new float[yData1.size()];
            for(int i=0;i<yData1.size();i++){
                getAllYData[i]=yData1.get(i);
            }
            float[] getAllZData=new float[zData1.size()];
            for(int i=0;i<zData1.size();i++){
                getAllZData[i]=zData1.get(i);
            }
            //定义二维数组
            double[][] getAllData=new double[getAllXData.length][3];
            //把一维数组合并为二维
            for(int m=0;m<getAllXData.length;m++){
                getAllData[m][0]=getAllXData[m];
                getAllData[m][1]=getAllYData[m];
                getAllData[m][2]=getAllZData[m];
            }
            String newpathName=VibrationConfig.getInversionPath()+"/"+ czCollectionTask.getId()+"/"+"inversionALLXYZData.txt";
            writeArrayToTxt2(getAllData,newpathName);

            //选中该数据
            List<Float> xData2 = xData1.subList(collectionTask.getStartData(),collectionTask.getEndData());
            List<Float> yData2 = yData1.subList(collectionTask.getStartData(),collectionTask.getEndData());
            List<Float> zData2 = zData1.subList(collectionTask.getStartData(),collectionTask.getEndData());
            //计算谱比 及平均值
            List<HVData> hvDataList = new ArrayList<>();
            //每组长度
            int L = xData2.size()/collectionTask.getInversionInterval();


            Float fs=1f;
            double[] xxx=null;
            double[] yyy=null;
            double[] zzz=null;

            double[] xxx2=null;
            double[] yyy2=null;
            double[] zzz2=null;
            //计算谱比
            xxx2 =new double[xData2.size()];
            yyy2 =new double[yData2.size()];
            zzz2 =new double[zData2.size()];
            for (int j = 0; j < xData2.size(); j++) {
                xxx2[j] = xData2.get(j);
                yyy2[j] = yData2.get(j);
                zzz2[j] = zData2.get(j);
            }
                            //写入计算的数据开始
                //定义二维数组
                double[][] getAllTotalData=new double[xxx2.length][3];
                //把一维数组合并为二维
                for(int m=0;m<xxx.length;m++){
                    getAllTotalData[m][0]=xxx2[m];
                    getAllTotalData[m][1]=yyy2[m];
                    getAllTotalData[m][2]=zzz2[m];
                }
                String AllDataNewPathName=VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask+"/"+"inversionXYZData.txt";
                writeArrayToTxt2(getAllTotalData,AllDataNewPathName);

            for (int i = 0; i < collectionTask.getInversionInterval(); i++) {
                List<Double> x = new ArrayList<>();
                List<Double> y = new ArrayList<>();
                List<Double> z = new ArrayList<>();
                for (int j = i*L; j < i*L+L; j++) {
                    x.add(xData2.get(j).doubleValue());
                    y.add(yData2.get(j).doubleValue());
                    z.add(zData2.get(j).doubleValue());
                }
                //计算谱比
                xxx =new double[x.size()];
                yyy =new double[y.size()];
                zzz =new double[z.size()];
                for (int j = 0; j < x.size(); j++) {
                    xxx[j] = x.get(j);
                    yyy[j] = y.get(j);
                    zzz[j] = z.get(j);
                }

//                //写入计算的数据开始
//                //定义二维数组
//                double[][] getAllTotalData=new double[xxx.length][3];
//                //把一维数组合并为二维
//                for(int m=0;m<xxx.length;m++){
//                    getAllTotalData[m][0]=xxx[m];
//                    getAllTotalData[m][1]=yyy[m];
//                    getAllTotalData[m][2]=zzz[m];
//                }
//                String AllDataNewPathName=VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask+"/"+"XYZData.txt";
//                writeArrayToTxt2(getAllTotalData,AllDataNewPathName);
                //写入计算的数据结束
                //计算频率
                float sampleInterval =equipment.getSampleInterval();
                fs = 1/(sampleInterval/1000);
                Map<String,double[]> hv = FFTUtil.hv(fs.intValue(),xxx,yyy,zzz);
                double[] f = hv.get("f");
                double[] h = hv.get("hv");
                HVData hvData = new HVData();
                hvData.setFrequency(f);
                hvData.setHv(h);
                hvDataList.add(hvData);

            }
//            /**
//             * 计算x曲线的值
//             */
//            MWNumericArray xDatamata = new MWNumericArray(xxx, MWClassID.DOUBLE);
//            computeVParam compute=new computeVParam();
//            MWNumericArray Length = new MWNumericArray(xxx.length, MWClassID.DOUBLE);
//            String xPlotfilePath= VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask+"/";
//            String xPlotfileName="xComputePlot";
//            MWStringArray xStringArrayPath=new MWStringArray(xPlotfilePath);
//            MWStringArray xStringArrayName=new MWStringArray(xPlotfileName);
//            Object[] respnseX=compute.ComputeVParam(7,xDatamata,fs,Length,xStringArrayPath,xStringArrayName);
//
//            //得到最大值
//            MWNumericArray xMaxData=(MWNumericArray)respnseX[0];
//            double[][] xMaxDataArray=(double[][])xMaxData.toDoubleArray();
//            double[] xMax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xMaxDataArray[0][0]))))};
//            //得到最小值
//            MWNumericArray xMinData=(MWNumericArray)respnseX[1];
//            double[][] xMinDataArray=(double[][])xMinData.toDoubleArray();
//            double[] xMin={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xMinDataArray[0][0]))))};
//            //得到平均值
//            MWNumericArray xAvgData=(MWNumericArray)respnseX[2];
//            double[][] xAvgDataArray=(double[][])xAvgData.toDoubleArray();
//            double[] xAvg={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xAvgDataArray[0][0]))))};
//            //得到标准差
//            MWNumericArray xStdData=(MWNumericArray)respnseX[3];
//            double[][] xStdDataArray=(double[][])xStdData.toDoubleArray();
//            double[] xStd={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xStdDataArray[0][0]))))};
//            //得到峰值频率
//            MWNumericArray xFmaxData=(MWNumericArray)respnseX[4];
//            double[][] xFmaxDataArray=(double[][])xFmaxData.toDoubleArray();
//            double[] xFmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xFmaxDataArray[0][0]))))};
//            //得到幅度
//            MWNumericArray xAmaxData=(MWNumericArray)respnseX[5];
//            double[][] xAmaxDataArray=(double[][])xAmaxData.toDoubleArray();
//            double[] xAmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(xAmaxDataArray[0][0]))))};
//
//            //定义二维数组
//            double[][] getComputeTotalDataX=new double[1][6];
//            //把一维数组合并为二维
//            for(int m=0;m<1;m++){
//                getComputeTotalDataX[m][0]=xMax[0];
//                getComputeTotalDataX[m][1]=xMin[0];
//                getComputeTotalDataX[m][2]=xAvg[0];
//                getComputeTotalDataX[m][3]=xStd[0];
//                getComputeTotalDataX[m][4]=xFmax[0];
//                getComputeTotalDataX[m][5]=xAmax[0];
//            }
//            /**
//             * 写入数据
//             */
//            String XComputePathName=VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask+"/"+"XComputeData.txt";
//            writeVibDataToTxt(getComputeTotalDataX,XComputePathName);
//
//
//            /**
//             * 计算y曲线的值
//             */
//            MWNumericArray yDatamata = new MWNumericArray(yyy, MWClassID.DOUBLE);
//            computeVParam compute2=new computeVParam();
//            MWNumericArray Length2 = new MWNumericArray(yyy.length, MWClassID.DOUBLE);
//            String yPlotfilePath= VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask+"/";
//            String yPlotfileName="yComputePlot";
//            MWStringArray yStringArrayPath=new MWStringArray(yPlotfilePath);
//            MWStringArray yStringArrayName=new MWStringArray(yPlotfileName);
//            Object[] respnseY=compute2.ComputeVParam(7,yDatamata,fs,Length2,yStringArrayPath,yStringArrayName);
//
//
//            //得到最大值
//            MWNumericArray yMaxData=(MWNumericArray)respnseY[0];
//            double[][] yMaxDataArray=(double[][])yMaxData.toDoubleArray();
//            double[] yMax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yMaxDataArray[0][0]))))};
//            //得到最小值
//            MWNumericArray yMinData=(MWNumericArray)respnseY[1];
//            double[][] yMinDataArray=(double[][])yMinData.toDoubleArray();
//            double[] yMin={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yMinDataArray[0][0]))))};
//            //得到平均值
//            MWNumericArray yAvgData=(MWNumericArray)respnseY[2];
//            double[][] yAvgDataArray=(double[][])yAvgData.toDoubleArray();
//            double[] yAvg={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yAvgDataArray[0][0]))))};
//            //得到标准差
//            MWNumericArray yStdData=(MWNumericArray)respnseY[3];
//            double[][] yStdDataArray=(double[][])yStdData.toDoubleArray();
//            double[] yStd={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yStdDataArray[0][0]))))};
//            //得到峰值频率
//            MWNumericArray yFmaxData=(MWNumericArray)respnseY[4];
//            double[][] yFmaxDataArray=(double[][])yFmaxData.toDoubleArray();
//            double[] yFmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yFmaxDataArray[0][0]))))};
//            //得到幅度
//            MWNumericArray yAmaxData=(MWNumericArray)respnseY[5];
//            double[][] yAmaxDataArray=(double[][])yAmaxData.toDoubleArray();
//            double[] yAmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(yAmaxDataArray[0][0]))))};
//
//
//            //定义二维数组
//            double[][] getComputeTotalDataY=new double[1][6];
//            //把一维数组合并为二维
//            for(int m=0;m<1;m++){
//                getComputeTotalDataY[m][0]=yMax[0];
//                getComputeTotalDataY[m][1]=yMin[0];
//                getComputeTotalDataY[m][2]=yAvg[0];
//                getComputeTotalDataY[m][3]=yStd[0];
//                getComputeTotalDataY[m][4]=yFmax[0];
//                getComputeTotalDataY[m][5]=yAmax[0];
//            }
//            /**
//             * 写入数据
//             */
//            String YComputePathName=VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask+"/"+"YComputeData.txt";
//            writeVibDataToTxt(getComputeTotalDataY,YComputePathName);
//
//
//
//            /**
//             * 计算z曲线的值
//             */
//            MWNumericArray zDatamata = new MWNumericArray(zzz, MWClassID.DOUBLE);
//            computeVParam compute3=new computeVParam();
//            MWNumericArray Length3 = new MWNumericArray(zzz.length, MWClassID.DOUBLE);
//            String zPlotfilePath= VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask+"/";
//            String zPlotfileName="zComputePlot";
//            MWStringArray zStringArrayPath=new MWStringArray(zPlotfilePath);
//            MWStringArray zStringArrayName=new MWStringArray(zPlotfileName);
//            Object[] respnseZ=compute3.ComputeVParam(7,zDatamata,fs,Length3,zStringArrayPath,zStringArrayName);
//
//
//            //得到最大值
//            MWNumericArray zMaxData=(MWNumericArray)respnseZ[0];
//            double[][] zMaxDataArray=(double[][])zMaxData.toDoubleArray();
//            double[] zMax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zMaxDataArray[0][0]))))};
//            //得到最小值
//            MWNumericArray zMinData=(MWNumericArray)respnseZ[1];
//            double[][] zMinDataArray=(double[][])zMinData.toDoubleArray();
//            double[] zMin={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zMinDataArray[0][0]))))};
//            //得到平均值
//            MWNumericArray zAvgData=(MWNumericArray)respnseZ[2];
//            double[][] zAvgDataArray=(double[][])zAvgData.toDoubleArray();
//            double[] zAvg={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zAvgDataArray[0][0]))))};
//            //得到标准差
//            MWNumericArray zStdData=(MWNumericArray)respnseZ[3];
//            double[][] zStdDataArray=(double[][])zStdData.toDoubleArray();
//            double[] zStd={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zStdDataArray[0][0]))))};
//
//            //得到峰值频率
//            MWNumericArray zFmaxData=(MWNumericArray)respnseZ[4];
//            double[][] zFmaxDataArray=(double[][])zFmaxData.toDoubleArray();
//
//            double[] zFmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zFmaxDataArray[0][0]))))};
//
//            //得到幅度
//            MWNumericArray zAmaxData=(MWNumericArray)respnseZ[5];
//            double[][] zAmaxDataArray=(double[][])zAmaxData.toDoubleArray();
//            double[] zAmax={Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(zAmaxDataArray[0][0]))))};
//
//
//            //定义二维数组
//            double[][] getComputeTotalDataZ=new double[1][6];
//            //把一维数组合并为二维
//            for(int m=0;m<1;m++){
//                getComputeTotalDataZ[m][0]=zMax[0];
//                getComputeTotalDataZ[m][1]=zMin[0];
//                getComputeTotalDataZ[m][2]=zAvg[0];
//                getComputeTotalDataZ[m][3]=zStd[0];
//                getComputeTotalDataZ[m][4]=zFmax[0];
//                getComputeTotalDataZ[m][5]=zAmax[0];
//            }
//            /**
//             * 写入数据
//             */
//            String ZComputePathName=VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask+"/"+"ZComputeData.txt";
//            writeVibDataToTxt(getComputeTotalDataZ,ZComputePathName);

            //计算平均值
            //double[] ff = hvDataList.get(0).getFrequency();
            double[] ff = new double[hvDataList.get(0).getFrequency().length-1];
            double[] hh =  new double[hvDataList.get(0).getHv().length-1];
            for (int i = 1; i < hvDataList.get(0).getFrequency().length; i++) {
                ff[i-1] = hvDataList.get(0).getFrequency()[i];
                double total = 0.0;
                for (int j = 0; j < hvDataList.size(); j++) {
                    total+=hvDataList.get(j).getHv()[i];
                }
                //保留6位小数
                BigDecimal two = new BigDecimal(total/hvDataList.size());
                double three = two.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();
                hh[i-1] = three;
            }
            //谱比平均值  echarts显示用
            HVData hvData = new HVData();
            hvData.setFrequency(ff);
            hvData.setHv(hh);
            collectionTask.setHvData(hvData);
            //组织数据二维数组
            double[][] result = new double[hh.length][2];
            for (int i = 0; i < hh.length; i++) {
                double[] temp = new double[2];
                temp[0] = ff[i];
                temp[1] = hh[i];
                result[i] =temp;
            }
            double[][] HVC=result;
            String pathName=VibrationConfig.getInversionPath()+"/"+ SocketUtil.inversionTask+"/"+"frequencyHV.txt";

            int NC=czCollectionTask.getInversionSlice();//厚度
            double Vstd=10.0;//误差棒
            int INPO=HVC.length;//数据长度
            try {
                transInfo= GetPlotImage.getPlotImage(NC,HVC,Vstd,INPO);
                SocketUtil.inversionTask = 0L;
                //修改反演状态
                //设置状态为反演中
                collectionTask.setInversionStatus("2");
                String filePath= Constants.RESOURCE_PREFIX+VibrationConfig.getInversionImgPath() +"/"+ collectionTask.getId()+"/";
                collectionTask.setDataFile(filePath);
                czCollectionTaskMapper.updateCzCollectionTask(collectionTask);
                //得到频率
                double[] frequency=hvData.getFrequency();
                //得到hv
                double[] hv=hvData.getHv();

               /* *四个一维数组转二维**/
                //定义二维数组
                double[][] getTotalData=new double[frequency.length][2];
                //把一维数组合并为二维
                for(int i=0;i<frequency.length;i++){
                    getTotalData[i][0]=frequency[i]; //频率值
                    getTotalData[i][1]=hv[i]; //HV值
                }
                writeArrayToTxt(getTotalData,pathName);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return czCollectionTask.getId();
    }

    public static void writeArrayToTxt(double[][] data, String string) {
        try {
            FileWriter fw = new FileWriter(string);
            fw.write("Frequency值"+ "\t\t");
            fw.write("HV值"+ "\t\t\t");
            fw.write("\n");
            //遍历四维数组
            for (int i = 0; i <data.length ; i++) {
                for (int j = 0; j <data[0].length ; j++) {
                    fw.write(data[i][j]+ "\t\t\t");
                }
                fw.write("\n");
            }
            fw.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void writeArrayToTxt2(double[][] data, String string) {
        try {
            FileWriter fw = new FileWriter(string);
            fw.write("X值"+ "\t\t\t\t\t");
            fw.write("Y值"+ "\t\t\t\t\t");
            fw.write("Z值"+ "\t\t\t");
            fw.write("\n");
            //遍历四维数组
            for (int i = 0; i <data.length ; i++) {
                for (int j = 0; j <data[0].length ; j++) {
                    fw.write(data[i][j]+ "\t\t\t");
                }
                fw.write("\n");
            }
            fw.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }


    public static void writeVibDataToTxt(double[][] data, String string) {
        try {
            FileWriter fw = new FileWriter(string);
            fw.write("最大值"+ "\t\t\t\t\t");
            fw.write("最小值"+ "\t\t\t\t");
            fw.write("平均值"+ "\t\t\t");
            fw.write("标准差"+ "\t\t\t\t");
            fw.write("峰值频率"+ "\t\t\t\t");
            fw.write("峰值幅度"+ "\t\t\t\t");
            fw.write("\n");
            //遍历四维数组
            for (int i = 0; i <data.length ; i++) {
                for (int j = 0; j <data[0].length ; j++) {
                    fw.write(data[i][j]+ "\t\t\t");
                }
                fw.write("\n");
            }
            fw.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public List<CzCollectionTask> selectTaskDataListByEquipmentSn(String equipmentSn,String type) {
        return czCollectionTaskMapper.selectTaskDataListByEquipmentSn(equipmentSn,type);
    }


    /**
     * 拿数据
     */
    public TransInfo getTransInfoData(){
        return transInfo;
    }

    /**
     * 线热源法
     * 计算导热系数
     */
    @Override
    public CzCollectionTask heatConduction(CzCollectionTask collectionTask) throws Exception {
        CzTemperatureData q = new CzTemperatureData();
        q.setTaskId(collectionTask.getId());
        List<CzTemperatureData> temperatureDataList = temperatureDataService.selectCzTemperatureDataList(q);
        //初始温度
        double startTemp=temperatureDataList.get(0).getTemperature();
        //开始和结束下标
        int start=collectionTask.getStartData();
        int end=collectionTask.getEndData();
        //截取集合
        List<CzTemperatureData> newTemperatureDataList=temperatureDataList.subList(start,end);
        //转温度数组给matlab-最终计算的y
        double[] getTemp =new double[newTemperatureDataList.size()];
        for (int i=0;i<getTemp.length;i++){
            getTemp[i]=newTemperatureDataList.get(i).getTemperature()-startTemp;
        }

        //转增温时间数组给matlab-最终计算的x
        double[] getTime =new double[newTemperatureDataList.size()];
        for (int i=0;i<getTime.length;i++){
            getTime[i]=Math.log(newTemperatureDataList.get(i).getWarmingTime());
        }
        //使用长度
        double tl=0.1;
        //电阻
        int tR=90;
        //电压
        int tV=9;
        //校正系数
        double checkCoefficient=collectionTask.getCheckCoefficient();
        //参考导热系数
        double TC1=collectionTask.getComHeatConductivity();
        //转矩阵
        MWNumericArray matX = new MWNumericArray(getTime, MWClassID.DOUBLE);
        MWNumericArray matY = new MWNumericArray(getTemp, MWClassID.DOUBLE);
        MWNumericArray L = new MWNumericArray(tl, MWClassID.DOUBLE);
        MWNumericArray R = new MWNumericArray(tR, MWClassID.DOUBLE);
        MWNumericArray V = new MWNumericArray(tV, MWClassID.DOUBLE);

        /*********线热源法************/
        //校正系数
        MWNumericArray mata = new MWNumericArray(checkCoefficient, MWClassID.DOUBLE);
        compute compute=new compute();
        Object[] res=compute.ComputeFinal(4,R,V,L,matX,matY,mata);
        //获取导热系数
        MWNumericArray getTC=(MWNumericArray)res[1];
        //转化导热系数
        double[][] limTC=(double[][])getTC.toDoubleArray();
        double TC=Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(limTC[0][0]))));

        //求热扩散系数
        MWNumericArray getCTE=(MWNumericArray)res[0];
        double[][] limCTE=(double[][])getCTE.toDoubleArray();
        double CTE=limCTE[0][0];
       //设置热扩散系数
        collectionTask.setThermalDiffusionCoefficient(CTE);

        //设置比热容
        MWNumericArray getC=(MWNumericArray)res[2];
        double[][] limC=(double[][])getC.toDoubleArray();
        double C=limC[0][0];
        collectionTask.setSpecificHeatCapacity(C);
        //设置导热系数
        collectionTask.setHeatConductivity1(TC);

        /*********热比较法************/
        //开始时间
        double startTime=temperatureDataList.get(start).getWarmingTime();
        //结束时间
        double endTime=temperatureDataList.get(end).getWarmingTime();
        //开始温度
        double startTemp2=temperatureDataList.get(start).getTemperature();
        //结束温度
        double endTemp=temperatureDataList.get(end).getTemperature();
        //时间与温度4个起始值计算导热系数
        MWNumericArray metaStartTime = new MWNumericArray(startTime, MWClassID.DOUBLE);
        MWNumericArray metaEndTime = new MWNumericArray(endTime, MWClassID.DOUBLE);
        MWNumericArray metaStartTemp = new MWNumericArray(startTemp2, MWClassID.DOUBLE);
        MWNumericArray metaEndTemp = new MWNumericArray(endTemp, MWClassID.DOUBLE);
        //参考导热系数
        MWNumericArray metaTC1 = new MWNumericArray(TC1, MWClassID.DOUBLE);
        //计算类
        computeTC2 compute2=new computeTC2();
        Object[] res2=compute2.ComputeTC2(3,R,V,L,metaStartTime,metaEndTime,metaStartTemp,metaEndTemp,metaTC1,matX,matY);
        //获取导热系数
        MWNumericArray getTC2=(MWNumericArray)res2[0];
        //转化导热系数
        double[][] limTC2=(double[][])getTC2.toDoubleArray();
        double TC2=Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(limTC2[0][0]))));
        //设置导热系数
        collectionTask.setHeatConductivity2(TC2);

        /***热比较法热扩散系数***/
        MWNumericArray getCTE2=(MWNumericArray)res2[1];
        double CTE2=((double[][])getCTE2.toDoubleArray())[0][0];
        collectionTask.setThermalDiffusionCoefficient2(CTE2);

        /***热比较法的比热容***/
        MWNumericArray getC2=(MWNumericArray)res2[2];
        double C2=((double[][])getC2.toDoubleArray())[0][0];
        collectionTask.setSpecificHeatCapacity2(C2);

        //设置数据分析状态为已分析
        collectionTask.setInversionStatus("2");
        updateCzCollectionTask(collectionTask);

        //导出全部数据
        String path=VibrationConfig.getInversionPath()+"/"+collectionTask.getId()+"/";
        //得到温度
        String[] temp1=new String[temperatureDataList.size()];

        //得到时间
        String[] time1=new String[temperatureDataList.size()];

        //得到增温
        String[] warmTime1=new String[temperatureDataList.size()];

        for (int i = 0; i < temperatureDataList.size(); i++) {
            temp1[i]=temperatureDataList.get(i).getTemperature().toString();
            time1[i]=getLongToString(temperatureDataList.get(i).getDataTime().toString());
            warmTime1[i]=temperatureDataList.get(i).getWarmingTime().toString();
        }

        //定义二维数组
        String[][] getTotalData=new String[temp1.length][3];
        //把一维数组合并为二维
        for(int i=0;i<temp1.length;i++){
            getTotalData[i][0]=temp1[i]; //温度值
            getTotalData[i][1]=time1[i]; //时间值
            getTotalData[i][2]=warmTime1[i];
        }
        String allDataPathName=path+"AllTempData.txt";
        File file=new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        writeArrayToTxtByChoose(getTotalData,allDataPathName);

        Double[] temp1data=new Double[temperatureDataList.size()];
        for (int i = 0; i < temperatureDataList.size(); i++) {
            temp1data[i]=temperatureDataList.get(i).getTemperature();
        }

        Double[] time1data=new Double[temperatureDataList.size()];
        for (int i = 0; i < temperatureDataList.size(); i++) {
            time1data[i]=temperatureDataList.get(i).getWarmingTime();
        }

        //生成所有数据图
        temp temp=new temp();
        MWStringArray stringArrayPath=new MWStringArray(path);
        String fileName="allData";
        MWStringArray stringArrayName=new MWStringArray(fileName);
        MWNumericArray matAllXData = new MWNumericArray(time1data, MWClassID.DOUBLE);
        MWNumericArray matAllYData = new MWNumericArray(temp1data, MWClassID.DOUBLE);
        temp.tempPlot(matAllXData,matAllYData,stringArrayPath,stringArrayName);

        //生成选择数据导出文件
        //生成txt文件
        String chooseDataPathName=path+"ComputeTempData.txt";
        //得到温度
        String[] temp2=new String[newTemperatureDataList.size()];
        //得到时间
        String[] time2=new String[newTemperatureDataList.size()];

        String[] warmTime2=new String[temperatureDataList.size()];

        for (int i = 0; i < newTemperatureDataList.size(); i++) {
            temp2[i]=newTemperatureDataList.get(i).getTemperature().toString();
            time2[i]=getLongToString(newTemperatureDataList.get(i).getDataTime().toString());
            warmTime2[i]=newTemperatureDataList.get(i).getWarmingTime().toString();
        }
        //定义二维数组
        String[][] getTotalData2=new String[temp2.length][3];
        //把一维数组合并为二维
        for(int i=0;i<temp2.length;i++){
            getTotalData2[i][0]=temp2[i]; //温度值
            getTotalData2[i][1]=time2[i]; //时间值
            getTotalData2[i][2]=warmTime2[i];
        }
        writeArrayToTxtByChoose(getTotalData2,chooseDataPathName);

        //生成结果数据
        String ResultPathName=path+"ResultTempData.txt";
        String[][] getTotalData3=new String[3][3];
        getTotalData3[0][0]="导热系数";
        getTotalData3[0][1]=String.valueOf(TC);
        getTotalData3[0][2]=String.valueOf(TC2);
        getTotalData3[1][0]="热扩散";
        String getResultCTE=new BigDecimal(Double.toString(CTE)).toPlainString();
        String getResultCTE2=new BigDecimal(Double.toString(CTE2)).toPlainString();
        getTotalData3[1][1]=getResultCTE;
        getTotalData3[1][2]=getResultCTE2;
        System.out.println("得到热扩散系数"+getResultCTE);
        getTotalData3[2][0]="比热容";
        getTotalData3[2][1]=String.valueOf(C);
        getTotalData3[2][2]=String.valueOf(C2);
        writeArrayResultToTxt(getTotalData3,ResultPathName);

        //生成部分数据图
        Double[] temp2data=new Double[newTemperatureDataList.size()];
        for (int i = 0; i < newTemperatureDataList.size(); i++) {
            temp2data[i]=newTemperatureDataList.get(i).getTemperature();
        }

        Double[] time2data=new Double[newTemperatureDataList.size()];
        for (int i = 0; i < newTemperatureDataList.size(); i++) {
            time2data[i]=newTemperatureDataList.get(i).getWarmingTime();
        }

        //生成计算数据图
        temp comTemp=new temp();
        String comFileName="computeData";
        MWStringArray stringComArrayName=new MWStringArray(comFileName);
        MWNumericArray matComXData = new MWNumericArray(time2data, MWClassID.DOUBLE);
        MWNumericArray matComYData = new MWNumericArray(temp2data, MWClassID.DOUBLE);
        comTemp.tempPlot(matComXData,matComYData,stringArrayPath,stringComArrayName);

        return collectionTask;
    }

    public static void writeArrayToTxtByChoose(String[][] data, String string) {
        try {
            FileWriter fw = new FileWriter(string);
            fw.write("温度值"+ "\t\t\t\t");
            fw.write("时间值"+ "\t\t\t\t");
            fw.write("增温时间"+ "\t\t\t");
            fw.write("\n");
            for (int i = 0; i <data.length ; i++) {
                for (int j = 0; j <data[0].length ; j++) {
                    fw.write(data[i][j]+ "\t\t\t");
                }
                fw.write("\n");
            }
            fw.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
    public String getLongToString(String longTime) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String time = sdf.format( Long.valueOf(longTime));
        return time;
    }

    public static void writeArrayResultToTxt(String[][] data, String string) {
        try {
            FileWriter fw = new FileWriter(string);
            fw.write("参数"+ "\t\t\t\t");
            fw.write("线热源法"+ "\t\t\t\t\t");
            fw.write("热比较法"+ "\t\t\t");
            fw.write("\n");
            //遍历四维数组
            for (int i = 0; i <data.length ; i++) {
                for (int j = 0; j <data[0].length ; j++) {
                    fw.write(data[i][j]+ "\t\t\t\t");
                }
                fw.write("\n");
            }
            fw.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 热比较法
     * 方法二计算导热系数
     */
    @Override
    public CzCollectionTask heatConductionByHeatCompare(CzCollectionTask collectionTask) throws MWException {
        CzTemperatureData q = new CzTemperatureData();
        q.setTaskId(collectionTask.getId());
        List<CzTemperatureData> temperatureDataList = temperatureDataService.selectCzTemperatureDataList(q);
        //开始和结束下标
        int start=collectionTask.getStartData();
        int end=collectionTask.getEndData();
        //开始时间
        double startTime=temperatureDataList.get(start).getWarmingTime();
        //结束时间
        double endTime=temperatureDataList.get(end).getWarmingTime();
        //开始温度
        double startTemp=temperatureDataList.get(start).getTemperature();
        //结束温度
        double endTemp=temperatureDataList.get(end).getTemperature();
        //参考导热系数
        double TC1=collectionTask.getComHeatConductivity();
        System.out.println("得到TC:"+TC1);
        //使用长度
        double tl=0.1;
        //电阻
        int tR=90;
        //电压
        int tV=9;
        //用来计算q
        MWNumericArray L = new MWNumericArray(tl, MWClassID.DOUBLE);
        MWNumericArray R = new MWNumericArray(tR, MWClassID.DOUBLE);
        MWNumericArray V = new MWNumericArray(tV, MWClassID.DOUBLE);


        //时间与温度4个起始值计算导热系数
        MWNumericArray metaStartTime = new MWNumericArray(startTime, MWClassID.DOUBLE);
        MWNumericArray metaEndTime = new MWNumericArray(endTime, MWClassID.DOUBLE);
        MWNumericArray metaStartTemp = new MWNumericArray(startTemp, MWClassID.DOUBLE);
        MWNumericArray metaEndTemp = new MWNumericArray(endTemp, MWClassID.DOUBLE);
        //参考导热系数
        MWNumericArray metaTC1 = new MWNumericArray(TC1, MWClassID.DOUBLE);
        //计算类
        computeTC2 compute=new computeTC2();
        Object[] res=compute.ComputeTC2(1,R,V,L,metaStartTime,metaEndTime,metaStartTemp,metaEndTemp,metaTC1);
        //获取导热系数
        MWNumericArray getTC=(MWNumericArray)res[0];
        //转化导热系数
        double[][] limTC=(double[][])getTC.toDoubleArray();
        double TC2=Double.parseDouble(String.format("%.15f", Double.parseDouble(String.valueOf(limTC[0][0]))));
        //设置导热系数
        collectionTask.setHeatConductivity2(TC2);
        return collectionTask;
    }

    @Override
    public List<TaskCountModel> taskCountByType(Integer type) {
        return czCollectionTaskMapper.taskCountByType(type);
    }

    @Override
    public void stopCzCollectionTask(CzCollectionTask task) {
        Map<String,List<TaskModel>> taskModelMap = redisCache.getCacheObject("task");
        if(taskModelMap!=null){
            List<TaskModel> taskModelList = taskModelMap.get(task.getEquipmentSn());
            if(taskModelList!=null){
                int i = -1;
                for (int j = 0; j < taskModelList.size(); j++) {
                    if(taskModelList.get(j).getTaskId().longValue() == task.getId().longValue()){
                        i = j;
                        break;
                    }
                }
                if(i!= -1){
                    taskModelList.remove(i);
                    System.err.println("删除任务redis==============》");
                    //设置任务采集结束


                }
            }
        }
        redisCache.setCacheObject("task",taskModelMap);
        task.setTaskStatus("2");
        updateCzCollectionTask(task);
        Map<String,List<TaskModel>> a = redisCache.getCacheObject("task");
        System.err.println("====================>振动任务列表");
        System.err.println(a);
    }

    /****************************发送报文开始********************************/
    private class pollThread implements Runnable {
        private DataCollection dataCollection;
        private Long taskId;
        public pollThread(DataCollection dc,Long id){
            dataCollection = dc;
            taskId = id;
            Socket socket = dataCollection.getSocket();
            if(socket!=null && !socket.isClosed()) {
                new Thread(this).start();
            }
        }
        public void run() {
            Socket socket = dataCollection.getSocket();
            while(SocketUtil.ontaskMap.containsKey(taskId)){
                if(socket!=null && !socket.isClosed()){
                    //将温度数据存储到数据库
                    CzTemperatureData temp = dataCollection.getTemperatureData();
                    System.err.println("=================>查询数据");
                    System.err.println(temp);
                    if(temp == null){//没有可以对比时间的数据，发送查询指令
                        //发送指令
                        try {
                            SocketUtil.sendData("010300050002D40A", socket.getOutputStream());
                            System.err.println("发送温度任务查询指令===>010300050002D40A");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }else {
                        //发送指令
                        try {
                            if(new Date().getTime()- temp.getDataTime()>=250){//判断当前时间与上一条数据时间差
                                SocketUtil.sendData("010300050002D40A", socket.getOutputStream());
                                System.err.println("发送温度任务查询指令===>010300050002D40A");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if(temp.getTemperature()>99.00){//温度大于99度 停止采集任务，设置任务状态
                            if(SocketUtil.ontaskMap.containsKey(taskId)){
                                SocketUtil.ontaskMap.remove(taskId);
                            }
                            CzCollectionTask cct = new CzCollectionTask();
                            cct.setId(taskId);
                            cct.setTaskStatus("2");
                            updateCzCollectionTask(cct);
                        }
                    }

                    try {//线程sleep300ms
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    /****************************发送报文结束********************************/
}
